<template>
  <el-dialog
    v-bind="$attrs"
    width="500px"
    v-on="$listeners"
    @close="close"
    @open="open"
  >
    <el-form
      ref="form"
      size="small"
      :model="form"
      @submit.prevent.native="confirm"
    >
      <el-form-item
        v-if="$attrs['entry-list']"
        label="Label"
        required
        prop="rowUniqueKey"
        :rules="entryLabelRules"
      >
        <el-input ref="key" v-model.trim="form.rowUniqueKey" :maxlength="64" />
      </el-form-item>

      <el-form-item
        v-else
        :label="$t('common.device_sn')"
        required
        prop="rowUniqueKey"
        :rules="snRules"
      >
        <el-input ref="key" v-model.trim="form.rowUniqueKey" />
      </el-form-item> </el-form
    ><template #footer>
      <div>
        <el-button size="small" @click="close">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          size="small"
          type="primary"
          native-type="submit"
          :disabled="form.rowUniqueKey.length < 1"
          :loading="loading"
          @click="confirm"
          >{{ $t('common.confirm') }}</el-button
        >
      </div></template
    >
  </el-dialog>
</template>

<script>
import { copyProfileEntry, copyReferenceEntry } from '@/api/parameter'
import { validateSN, validateEntryLabel } from '../validate'
export default {
  inheritAttrs: false,
  props: {
    terminal: {
      type: Object
    },
    type: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        rowUniqueKey: ''
      },
      loading: false,
      entryLabelRules: validateEntryLabel,
      snRules: validateSN
    }
  },
  methods: {
    resetForm() {
      this.$refs.form.resetFields()
    },
    close() {
      this.$emit('update:model-value', false)
      this.resetForm()
    },
    open() {
      this.$nextTick(() => {
        this.$refs.key.focus()
      })
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const request =
            this.type === 'terminal' ? copyProfileEntry : copyReferenceEntry

          request(
            this.terminal.paramsTemplateId,
            this.terminal.tableSchemaId,
            this.terminal.id,
            {
              rowUniqueKey: this.form.rowUniqueKey.trim()
            }
          )
            .then(() => {
              this.loading = false
              this.close()
              this.$emit('confirm')
            })
            .catch((err) => {
              this.loading = false
              this.$message.error(err)
            })
        }
      })
    }
  }
}
</script>

<style>
</style>
